package com.stone.framework.gateway.config;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.discovery.DiscoveryClientRouteDefinitionLocator;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

@Configuration
public class SwaggerConfig {

    @Component
    public static class DefaultSwaggerResourcesProvider implements SwaggerResourcesProvider {

        @Autowired
        private DiscoveryClientRouteDefinitionLocator discoveryClientRouteDefinitionLocator;

        @Override
        public List<SwaggerResource> get() {
            List<RouteDefinition> routeDefinitions = new ArrayList<>();
            discoveryClientRouteDefinitionLocator.getRouteDefinitions().subscribe(e -> routeDefinitions.add(e));

            List<SwaggerResource> resources = routeDefinitions.stream()
                .map(routeDefinition -> routeDefinition.getPredicates().stream()
                    .filter(predicateDefinition -> "Path".equalsIgnoreCase(predicateDefinition.getName()))
                    .map(predicateDefinition -> this.buildSwaggerResource(predicateDefinition.getArgs().get("pattern")))
                    .findFirst().get())
                .collect(Collectors.toList());

            return resources;
        }

        private SwaggerResource buildSwaggerResource(String path) {
            SwaggerResource resource = new SwaggerResource();
            resource.setName(path.replace("/**", "").substring(1));
            resource.setLocation(path.replace("/**", "/v2/api-docs").substring(1));
            return resource;
        }
    }

}
